import { startsWith } from 'lodash';
import { stringify } from 'qs';
import { history, RequestConfig } from 'umi';
import { deleteCurrentLoginUserId, deleteToken, getRoutes, getToken } from './utils/authority';
import { message } from 'antd';

// 保存服务器端动态路由
// let extraRoutes;

export function patchRoutes({routes}:{routes: any}) {
  // console.info('app.patchRoutes');
  // console.info(routes);
  // merge(routes, extraRoutes);
}

export function render(oldRender: Function) {
  // console.info('render');
  // fetch('/api/routes').then(res=>res.json()).then((res) => {
  //   extraRoutes = res.routes;
  //   oldRender();
  // }).catch(e=>console.error('error happen', e));
  oldRender();
}

export function onRouteChange({ location }: {location: any, routes: any, action:any}) {
  // 这里判断url是否在用户菜单里
  // console.info('onRouteChange');
  // console.info(location);
  // const { pathname } = location;
  // 获取
  // console.info('onRouteChange');
  // console.info(location);
  // 路由切换时判断token是否存在
  // 或者过期
  // 跳转到登录界面
  const { pathname } = location;
  const pathName = pathname;
  // console.info('pathName=', pathName);
  if (pathName === "/" || startsWith(pathName, '/user/login') || startsWith(pathName, '/user')) {
    // console.info('登录ing');
    return;
  }
  const currentOfRoutes = getRoutes();
  if (currentOfRoutes && currentOfRoutes.indexOf(pathName) < 0) {
    // 判断当前url是否在路由集合中
    console.info('非法访问', pathName);
    message.warning('请勿访问未经授权的页面');
    history.replace({
      pathname: '/user/login',
      // 记录从那个页面跳转跳转到登录页面的，登录后在跳转回去
    });
  }
  const token = getToken();
  if (!token) {
    // console.info('登录ing2');
    deleteToken();
    deleteCurrentLoginUserId();
    history.replace({
      pathname: '/user/login',
      // 记录从那个页面跳转跳转到登录页面的，登录后在跳转回去
      search: stringify({
        redirect: pathName,
      }),
    });
  }
}

export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData) => {
      return {
        ...resData,
        success: resData.success,
        errorCode: resData.errorCode,
        errorMsg: resData.errorMsg,
      };
    },
  },
};